import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar 进度条
import 'nprogress/nprogress.css' // progress bar style 进度条样式
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

// 1.全局前置路由守卫————在路由跳转之前进行判断
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)
  // 用户登录了，才会有token，未登录不会有token
  // determine whether the user has logged in
  const hasToken = getToken()

    // 用户已登录
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      console.log("已登录,无需再登录,回到home");
      next({ path: '/' })
      NProgress.done()
    } else {
      //登录了，但是去的不是login,且拥有用户信息放行
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
        console.log("登录成功，携带用户信息");
      } else {
        try {
          //登录了，没有用户信息,派发action
          // get user info 发请求获取用户信息
          await store.dispatch('user/getInfo')
          next() 
        } catch (error) {
          alert("超时，请重新登录")
          // remove token and go to login page to re-login  派发退出登录action 
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
           // 去到登录页面
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    //用户未登录
    console.log("登录失败");
    console.log(to,from);
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})
// 2.全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach(() => {
  // finish progress bar 进度条结束
  NProgress.done()
})
